import Taro, { Component } from '@tarojs/taro'
import { View, Picker, Text, Image } from '@tarojs/components'
import { AtButton, AtSwitch, AtIcon } from 'taro-ui'
import { DNavBar, DModal, DAtInpute, DAgree, Button } from '@/components'
import classNames from 'classnames'
import dayjs from 'dayjs'
import http from '@/api'
import sdk from '@/common/sdk'
import '../myquotes/myquotes.scss';
// import "taro-ui/dist/style/components/modal.scss";
import './logisticsform.scss'
const startImg = require('./start_place.png')
const endImg = require('./end_place.png')
const itemplace = require('./place.png')
const itemprogress = require('./progress.png')
import commonUtils from '@/common/index'
const payIp = window.payIp

export default class LogisticsForm extends Component {

  constructor(props) {
    super(props)
    this.state = {
      status: false,
      type: 1,
      isOpened: false,
      startTime: dayjs().format('YYYY-MM-DD'),
      userForm: {
        list: [],
        startAddre: '',
        startAddreDetail: '',
        endAddre: '',
        endAddreDetail: '',
        time: '',
        status: '',
        point: {},
        info: '',
        money: ''
      },
      title: '发布物流'
    }
  }
  componentWillMount() {
    // if(window.localStorage.getItem('ISPAY')){
    // 	// this.state.isOpened： = true
    // 	this.setState({
    // 		isOpened:true
    // 	},()=>window.localStorage.removeItem('ISPAY'))
    // }
  }

  componentDidShow() {

    this.getBrandInfo()
    this.getAddreInfo()
    sdk.setTitleInfo(this.state.title)
  }

  getAddreInfo() {
    let _addreinfo = JSON.parse(sessionStorage.getItem('_addreinfo'))
    if (!_addreinfo) {
      return
    }
    let { userForm, type } = this.state
    const desc = _addreinfo.desc, region = _addreinfo.region
    let addreDetail = ''
    if (desc.substr && region === desc.substr(0, region.length)) {
      addreDetail = desc
    } else {
      addreDetail = region + desc
    }
    if (type === 1) {
      userForm.startAddre = _addreinfo.title
      userForm.startAddreDetail = addreDetail
      userForm.point.lat = _addreinfo.point.lat
      userForm.point.lng = _addreinfo.point.lng
    } else if (type === 2) {
      userForm.endAddre = _addreinfo.title
      userForm.endAddreDetail = addreDetail
      userForm.point.lat1 = _addreinfo.point.lat
      userForm.point.lng1 = _addreinfo.point.lng
    }

    this.setState({
      userForm
    }, () => {

      this.accountFrees()
      sessionStorage.removeItem('_addreinfo',)
    })
  }
  accountFrees() {
    let { point, list: carInfo } = this.state.userForm
    let account = 0

    let isK = Object.keys(point)

    let latLngSum = isK.length === 4 ? commonUtils.getDistance(point.lat, point.lng, point.lat1, point.lng1) : false
    //debugger
    if (carInfo.length && Number(latLngSum) >= 0) {
      if (carInfo.length === 1) {
        account = latLngSum * 8
      } else if (carInfo.length === 2) {
        account = latLngSum * 10
      }
      this.state.userForm.money = account
      if (Number(latLngSum) <= 0) {
        return Taro.showToast({
          title: '预估计费必须大于0,地址距离是否太近',
          icon: "none"
        })
      }
      this.setState({
        userForm: this.state.userForm
      })
    }



  }
  getBrandInfo() {
    let _brandList = sessionStorage.getItem('brandList')
    if (!_brandList) {
      return
    }
    let { carBrandId = '', waiguanyanse = '',
      neigaunyanse = '', carBrandLogo = '', carModel = '', carSourceType = '', carGuiPrice = '', carModelId = '' } = JSON.parse(_brandList)
    let _list = []
    _list.push({
      addre: carModel
    })

    this.setState({
      waiguanyanse,
      neigaunyanse,
      userForm: {
        ...this.state.userForm,
        list: [...this.state.userForm.list, ..._list]
      }
    }, () => {
      this.accountFrees()
      sessionStorage.removeItem('brandList')
    })
  }

  setUserCar() {
    let { userForm } = this.state
    if (userForm.list.length === 2) {
      userForm.money = 10 * 175
    } else if (userForm.list.length === 1) {
      userForm.money = 8 * 175
    } else {
      userForm.money = '---'
    }
    this.setState({
      userForm
    })
  }


  userFormKey(key, value) {
    if (key) {
      this.setState({
        userForm: Object.assign(this.state.userForm, { [key]: value })
      })
    }
  }

  onBrandchList() {
    if (this.state.userForm.list.length >= 2) {
      return Taro.showToast({
        title: '最多选择两台车辆托运!',
        icon: "none"
      })
    }
    Taro.navigateTo({
      url: '/pages/choosebrand/choosebrand'
    })
  }
  onFocusInput(isFocus) {
    this.setState({
      isFocus
    })
  }
  onAddreCancle(i) {
    let { userForm } = this.state
    userForm.list.splice(i, 1)
    this.setState({
      userForm
    }, () => {
      this.accountFrees()
      // this.setUserCar()
    })

  }


  onHandleChange(value) {
    this.setState({
      status: value
    })
  }

  onChangeTime(e) {
    let { value } = e.detail
    let _value = dayjs(value).format('YYYY-MM-DD')
    this.userFormKey('time', _value)
  }

  onSelectMap(value, address) {
    this.setState({
      type: value
    }, () => {
      Taro.navigateTo({
        url: `/pages/selectmap/selectmap?type=${this.state.type}&address=${address}`
      })
    })
  }
  payFuc(type) {
    this.setState({
      isOpened: false
    })
    if (type) {
      Taro.navigateTo({
        url: `/pages/mylogistics/mylogistics`
      })
    }
  }
  // payCancel(){

  // },
  onSubmit() {
    let redirectUrl = encodeURI('http%3A%2F%2Fwww.coolkar.group:9010')
    let _userForm = ['startAddre', 'endAddre', 'time']
    let { userForm, status, typeForm } = this.state
    let _status = false, _item = '',
      objtext = {
        startAddre: '请输入始发地地址',
        endAddre: '请输入目的地地址',
        time: '请选择发车日期'
      }
    // _userForm.map(item => {
    //     if (!userForm[item]) {
    //         _status = true
    //     }
    // })
    if (Number(userForm.money) === 0 || !Number(userForm.money)) {
      _status = true
      _item = '预估计费必须大于0,地址距离是否太近'
    }
    if (userForm.list.length === 0) {
      _status = true
      _item = '请添加托运车辆'
    }
    for (let i = 0, j = _userForm.length; i < j; i++) {
      if (!userForm[_userForm[i]]) {
        _status = true
        _item = objtext[_userForm[i]]
        break
      }
    }


    if (_status) {
      return Taro.showToast({
        title: _item,
        icon: 'none'
      })
    }
    // if (!status) {
    //     return Taro.showToast({
    //         title: '请阅读并同意《车辆运输服务协议》',
    //         icon: 'none'
    //     })
    // }
    let _cdCarModel = ''
    if (userForm.list.length > 1) {

      let _list = []
      userForm.list.map(item => {
        _list.push(item.addre)
      })
      _cdCarModel = _list.join('#')
    } else {
      _cdCarModel = userForm.list[0].addre
    }

    let transCarDemand = {
      payIp,
      payType: '1',
      ago: '',
      cdCarModel: _cdCarModel,
      cdComment: userForm.info,
      cdEnd: userForm.endAddre,
      cdEndDetail: userForm.endAddreDetail,
      cdEndLat: userForm.point.lat1,
      cdEndLng: userForm.point.lng1,
      cdNo: '',
      cdPreMoney: Number(userForm.money) ? userForm.money : 0,
      cdShowStatus: userForm.status === '' ? 0 : userForm.status,
      cdStart: userForm.startAddre,
      cdStartDetail: userForm.startAddreDetail,
      cdStartLat: userForm.point.lat1,
      cdStartLng: userForm.point.lng,
      cdStartTime: userForm.time,
      createTime: '',
      creator: '',
      creatorContact: '',
      creatorId: '',
      entDis: '',
      entId: '',
      entName: '',
      entPhoto: '',
      entPhotoUrl: '',
      id: '',
      status: 1, //  0已删除1正常2已下架
      updateTime: '',
      updator: '',
      updatorId: '',
      viewedTime: ''
    }
    // if (userForm.money > 3000) {
    //   return Taro.showToast({
    //     title: '支付金额超过3000元,请联系管理员线下支付'
    //   })
    // }
    http.addLogistics(transCarDemand).then((res) => {
      Taro.showToast({
        title: '已发布物流',
        duration: 800,
        mask: true
      }).then(() => {
        setTimeout(() => {
          // window.localStorage.setItem('ISPAY',1)
          // window.location.href = res
          // "&redirect_url=" + "/#/pages/mylogistics/mylogistics"
          Taro.redirectTo({
            url: '/pages/mylogistics/mylogistics'
          })

        }, 800);
        // if (typeForm === 'usercar') {
        // return setTimeout(() => {
        //     Taro.navigateTo({
        //         url: `/pages/mylogistics/mylogistics`
        //     })
        // }, 1000);
        // } else if (window.bridge) {
        //     window.bridge.callHandler('close', {}, function responseCallback(res) { })
        // } else {
        //     setTimeout(() => {
        //         Taro.navigateBack({
        //             delta: 1
        //         })
        //     }, 1000)
        // }
      })
    })
  }

  render() {
    const {
      userForm,
      status,
      startTime,
      title
    } = this.state
    const _bindCarform = function (value) {
      this.userFormKey(arguments[arguments.length - 1].bind, value)
    }
    const _swichBindCarform = function (key, value) {
      this.userFormKey(key, +value)
    }
    return (
      <View className='b_logisticsform'>
        <DNavBar title={title}></DNavBar>
        <View className='b_logisticsform__box'>
          <View className='b_logisticsform__content'>
            <View className='b_logisticsform__addr'>
              <DAtInpute className="_textOv" value={userForm.startAddre} title={'始发地址'} iconImg={startImg} image={itemplace} placeholder='请输入始发运输地址' onRightHanlde={this.onSelectMap.bind(this, 1, userForm.startAddre)}></DAtInpute>
              <Image src={itemprogress} className='b_logisticsform__addr-progress'></Image>
              <DAtInpute className="_textOv" value={userForm.endAddre} title={'目的地址'} iconImg={endImg} image={itemplace} placeholder='请输入目的运输地址' onRightHanlde={this.onSelectMap.bind(this, 2, userForm.endAddre)}></DAtInpute>
            </View>
            <View className='b_logisticsform__second'>
              <View className='b_logisticsform__time'>
                <View className='b_logisticsform__time_title'>发车日期</View>
                <Picker mode='date' value='YYYY-MM-DD' start={startTime} onChange={this.onChangeTime.bind(this)}>
                  <View className='b_logisticsform__time_right'>
                    <View className={classNames('b_logisticsform__time_placeholder', userForm.time ? 'b_logisticsform__active' : '')}>{userForm.time || '请选择发车日期'}</View>
                    <AtIcon value='chevron-right' color='#cccccc' size='25'></AtIcon>
                  </View>
                </Picker>
              </View>
              <View className='b_logisticsform__car'>
                <View className='b_logisticsform__car_title'>托运车辆</View>
                <View className='b_logisticsform__car_right'>
                  <Text className='b_logisticsform__car_placeholder'>请添加托运车辆</Text>
                  <AtIcon onClick={this.onBrandchList.bind(this)} value='add-circle' color='#cccccc' size='25'></AtIcon>
                </View>
              </View>
              {
                userForm.list.length > 0 && <View className='b_logisticsform__list'>
                  {
                    userForm.list && userForm.list.map((item, i) => {
                      return <View className='b_logisticsform__list_item'>
                        <View className='b_logisticsform__list_value'>{item.addre}</View>
                        <AtIcon onClick={this.onAddreCancle.bind(this, i)} value='subtract-circle' color='#cccccc' size='25'></AtIcon>
                      </View>
                    })
                  }

                </View>
              }
            </View>
            <View className='b_logisticsform__status'>
              <AtSwitch bind='status' onChange={_swichBindCarform.bind(this, 'status')} checked={userForm.status} color="rgb(255,190,0)" title={"是否隐藏联系方式"}></AtSwitch>

              <DAtInpute bind='info' maxLength={20} onBlur={this.onFocusInput.bind(this, false)} onFocus={this.onFocusInput.bind(this, true)} onChange={_bindCarform.bind(this)} value={userForm.info} title={'备注'} placeholder='请输入其他运输要求（20字以内）'
                id="input0" ></DAtInpute>
            </View>

            <DModal isShow={this.state.isOpened} title="支付提示" text="是否已完成支付？" firstbtn="支付失败" lastbtn="支付完成" onFirst={this.payFuc.bind(this)} onCancel={this.payFuc.bind(this)} onLast={this.payFuc.bind(this, 1)}></DModal>
            {/*<AtModal
						  isOpened
						  title="支付提示!"
						  cancelText="支付失败"
						  confirmText="支付成功"
						  onClose={ this.payFuc.bind(this)}
						  onCancel={ this.handleCancel }
						  onConfirm={this.payFuc.bind(this,1)}
						  content="请确认支付是否已完成!"
						/>*/}

            <View className='b_logisticsform__footer' style={{ position: this.state.isFocus ? 'relative' : 'fixed' }}>
              {/*<DAgree className='b_logisticsform__footer_info' type='4' value={status} text={'车辆运输服务协议'} onHandleChange={this.onHandleChange.bind(this)}></DAgree>*/}
              <View className='b_logisticsform__footer_item'>
                <View className='b_logisticsform__footer_money'>
                  <Text className='b_logisticsform__footer_money__flag'>预计费用¥</Text>
                  <Text className='b_logisticsform__footer_money__number'>{userForm.money ? Number(userForm.money).toFixed(2) : 0}元</Text>
                </View>
                <AtButton className='item_btn' onClick={this.onSubmit.bind(this)}>提交</AtButton>
              </View>
            </View>
          </View>
        </View>
      </View>
    )
  }
}
